<?php

namespace polymerize\auth\module\login;


use app\common\InstanceTrait;
use app\common\LoginType;
use app\model\OrderVipcart;
use app\model\User as UserModel;
use app\model\UserBehaviorLog;
use app\model\UserToken;
use app\model\UserVip;
use app\service\WechatService;
use think\Exception;

class WechatAppLogin
{
    use InstanceTrait;

    /**
     * 微信小程序微信登录
     *
     * @param string $code
     * @param string $encrypteData
     * @param string $iv
     * @param string $ref
     * @return array
     */
    public function wechatAppLogin(string $code, string $encrypteData, string $iv, string $ref): array
    {
        try {
            $res  = WechatService::instance()->_wechat_app_login($code, $encrypteData, $iv, $ref);
            if ($res['code'] != 200) return ['code' => 400, 'msg' => $res['msg']];
            $user = $res['data'];

            $user_status = true;
            if ($user['status'] != 1) $user_status = false;
            $param = [
                'uid'         => $user['id'],
                'type'        => 2,
                'user_status' => $user_status ? 1 : 2,
                'status'      => $user_status ? 1 : 2,
                'login_type'  => LoginType::LOGIN_TYPE_WECHATAPP->value
            ];
            UserBehaviorLog::log($param);
            if (!$user_status) return ['code' => 400, 'msg' => '当前账号状态异常，请联系管理员'];

            $token         = UserToken::loginToken($user, LoginType::LOGIN_TYPE_WECHATAPP->value);
            $data['token'] = $token['token'] ?? '';

            $uid       = $user['id'];
            //会员过期状态，1正常 2过期
            $where2[]           = ['user_id', '=', $uid];
            $where2[]           = ['status', '=', 1];
            $where2[]           = ['order_status', '<>', 3];
            $data['is_vip'] = OrderVipcart::getFieldByOrder($where2, 'status', 'pay_time desc') ? 1 : 2;

            $data['uid'] = $uid;

            return ['code' => 200, 'msg' => '', 'data' => $data];
        } catch (\Throwable $exception) {
            return ['code' => 400, 'msg' => '登录失败' . $exception->getMessage()];
        }
    }
}
